import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart' as d;
import 'package:ls_work/a_yyt/models/handover_new_entity.dart';
import 'package:ls_work/a_yyt/page/handover_area_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:base_flutter/base_flutter.dart';

class HomeHandoverPage extends StatefulWidget {
  @override
  _HomeHandoverPageState createState() => _HomeHandoverPageState();
}

class _HomeHandoverPageState extends State<HomeHandoverPage> {
  List<HandoverNewInfo> dataList = [];
  List<String> chipLlist = ['本周', '上周'];
  int _valueChoice = 0;
  String _timeContent = 'yyyyMM';
  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _fectData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('交接班'),
        elevation: 0.5,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            decoration: BoxDecoration(
                border: Border(
                    bottom: Divider.createBorderSide(context,
                        width: 1, color: Colours.line))),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Wrap(
                  spacing: 30,
                  children: List<Widget>.generate(2, (int index) {
                    return ChoiceChip(
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      label: Text('${chipLlist[index]}'),
                      backgroundColor: Colours.text_gray,
                      selectedColor: Colors.blue[300],
                      onSelected: (bool selected) {
                        if (_valueChoice == index) return;
                        setState(() {
                          _valueChoice = selected==true ? index : 0;
                          if (selected) {
                            _fectData();
                          }
                        });
                      },
                      selected: _valueChoice == index,
                    );
                  }),
                ),
                Gaps.hGap16,
                Expanded(child: Container(
                  width: double.infinity,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colours.bg_color,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: InkWell(
                    onTap: _showTimePicker,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            _timeContent,
                            textAlign: TextAlign.center,
                            style: TextStyles.textGray16,
                          ),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colours.text_gray,
                        )
                      ],
                    ),
                  ),
                ),flex: 1,)
              ],
            ),
          ),
          Flexible(
            child: ListView.builder(
              itemCount: dataList.length,
              itemBuilder: (_, index) {
                String dateTime = DateUtil.formatDateStr(
                  dataList[index].reportDate??"",
                  format: DateFormats.y_mo_d,
                );
                return Container(
                  child: ClickItem(
                    title: '$dateTime   ${dataList[index].week ?? ''}',
                    titleStyle: TextStyles.textDark20,
                    contentStyle: TextStyles.textGray18,
                    onTap: () {
                      AppNavigator.push(
                          context, HandoverAreaPage(info: dataList[index]));
                    },
                    content: '${dataList[index].dutyTypeDesc ?? ''}',
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  _fectData() {
    var map = {'queryType': _valueChoice.toString()};
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyReport}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.data.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {

            HandoverNewEntity model = HandoverNewEntity.fromJson(map);
            if ((model.data??[]).length > 0) {
              setState(() {
                dataList = model.data??[];
              });
            } else {
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(NetErrorUtils.getNetError(e));
    });
  }

  ///调起时间选择器
  _showTimePicker() {
   d.DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1900-01-01 00:00"),
      maxDateTime: DateTime.now(),
      initialDateTime: _selectedDate,
      dateFormat: DateFormats.y_mo,
      locale: d.DateTimePickerLocale.zh_cn,
      pickerTheme: d.DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: d.DateTimePickerMode.date, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          print(dateTime);
          if (dateTime == null) {
            return;
          }
          this._selectedDate = dateTime;
          _timeContent = DateUtil.formatDate(dateTime, format: 'yyyy-MM');
          _valueChoice =
              int.parse(DateUtil.formatDate(dateTime, format: 'yyyyMM'));
          _fectData();
        });
      },
    );
  }
}
